package handlers

import (
	"net/http"
	"strconv"

	"toolsweb-admin/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// ListDocCategories
// @Summary 获取文档分类列表
// @Description 获取所有文档分类及其关联文档
// @Tags 文档分类
// @Produce json
// @Success 200 {array} models.DocCategory
// @Router /api/doc-categories [get]
func ListDocCategories(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	var categories []models.DocCategory
	if err := db.Preload("Documents").Find(&categories).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		return
	}
	c.JSON(http.StatusOK, categories)
}

// @Summary 创建文档分类
// @Description 创建新的文档分类
// @Tags 文档分类
// @Accept json
// @Produce json
// @Param category body models.DocCategory true "分类信息"
// @Success 201 {object} models.DocCategory
// @Router /api/doc-categories [post]
func CreateDocCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	var category models.DocCategory
	if err := c.ShouldBindJSON(&category); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	if err := db.Create(&category).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建失败"})
		return
	}
	c.JSON(http.StatusCreated, category)
}

// @Summary 更新文档分类
// @Description 更新指定ID的文档分类
// @Tags 文档分类
// @Accept json
// @Produce json
// @Param id path int true "分类ID"
// @Param category body models.DocCategory true "分类信息"
// @Success 200 {object} models.DocCategory
// @Router /api/doc-categories/{id} [put]
func UpdateDocCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	var category models.DocCategory
	if err := db.First(&category, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"})
		return
	}

	if err := c.ShouldBindJSON(&category); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}

	db.Save(&category)
	c.JSON(http.StatusOK, category)
}

// @Summary 删除文档分类
// @Description 删除指定ID的文档分类
// @Tags 文档分类
// @Param id path int true "分类ID"
// @Success 204
// @Router /api/doc-categories/{id} [delete]
func DeleteDocCategory(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	if err := db.Delete(&models.DocCategory{}, id).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败"})
		return
	}
	c.JSON(http.StatusNoContent, nil)
}

// @Summary 获取分类文档
// @Description 获取指定分类下的所有文档
// @Tags 文档分类
// @Produce json
// @Param id path int true "分类ID"
// @Success 200 {array} models.DocItem
// @Router /api/doc-categories/{id}/documents [get]
func GetCategoryDocuments(c *gin.Context) {
	db := c.MustGet("db").(*gorm.DB)
	id, _ := strconv.Atoi(c.Param("id"))

	var docs []models.DocItem
	if err := db.Where("doc_category_id = ?", id).Find(&docs).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		return
	}
	c.JSON(http.StatusOK, docs)
}
